class_name MDLabel
extends Control

@export var text: String = "# 示例文档

这是一个 **加粗** 和 *斜体* 的文本。

* 列表项 1
* 列表项 2

链接示例: [Godot官网](https://godotengine.org)

```这是代码块内容```"
@export var code_font: Font = null
@export var code_font_size: int = 14
@export var code_background_color: Color = Color(0.1, 0.1, 0.1, 0.8)

@onready var rich_text_label: RichTextLabel = $RichTextLabel

func _ready():
	parse_markdown()

func _set_text(value):
	text = value
	parse_markdown()

func parse_markdown():
	var bbcode = ""
	
	# 处理代码块标记
	text = text.replace("```", "[CODEBLOCK]")
	
	var lines = text.split("\n")
	var in_code_block = false
	var code_block_content = ""
	
	for line in lines:
		if line.strip_edges() == "[CODEBLOCK]":
			if not in_code_block:
				in_code_block = true
				code_block_content = ""
			else:
				# 结束代码块
				bbcode += format_code_block(code_block_content)
				in_code_block = false
			continue
			
		if in_code_block:
			code_block_content += line + "\n"
			continue
			
		# 常规文本处理
		bbcode += parse_line(line) + "\n"
	
	rich_text_label.bbcode_text = bbcode

func parse_line(line: String) -> String:
	var result = line
	
	# 标题
	if line.begins_with("# "):
		result = "[b][font_size=24]" + line.substr(2) + "[/font_size][/b]"
	elif line.begins_with("## "):
		result = "[b][font_size=20]" + line.substr(3) + "[/font_size][/b]"
	
	# 加粗
	result = result.replace("**", "[b]")
	
	# 斜体
	result = result.replace("*", "[i]")
	
	# 链接
	result = result.replace("[", "[url=").replace("](", "][").replace(")", "[/url]")
	
	# 列表项
	if result.strip_prefix("* ").is_empty() and result.strip_prefix("- ").is_empty():
		result = result.replace("* ", "[list][*]").replace("- ", "[list][*]")
	
	return result

func format_code_block(content: String) -> String:
	return "[center][color={0}][font={1}][font_size={2}]{3}[font_size=0][/font][/color][/center]".format(
		code_background_color.to_html(),
		code_font.resource_path
	)
